using IQIGame.Onigao.Framework;
using System.IO;
using UnityEditor;
using UnityEngine;

namespace IQIGame.Onigao.Game.Editors
{
    /// <summary>
    /// UI创建菜单
    /// </summary>
    public static class UICreateMenu
    {
        [MenuItem("Assets/Create/IQIGame/UIRoot", false, 1)]
        static void CreateUI()
        {
            string pathName = "NewUI.prefab";
            var icon = EditorGUIUtility.IconContent("Prefab Icon").image as Texture2D;
            ProjectWindowUtil.StartNameEditingIfProjectWindowExists(0, ScriptableObject.CreateInstance<DoCreatePrefab>(), pathName, icon, null);
        }

        /// <summary>
        /// 定义结束编辑时的行为
        /// </summary>
        public class DoCreatePrefab : UnityEditor.ProjectWindowCallback.EndNameEditAction
        {
            public override void Action(int instanceId, string pathName, string resourceFile)
            {
                // 创建一个新的游戏对象
                GameObject root = new GameObject(Path.GetFileNameWithoutExtension(pathName));
                root.layer = LayerMask.NameToLayer("UI");
                var rectTrans = root.AddComponent<RectTransform>();
                rectTrans.anchorMin = Vector3.zero;
                rectTrans.anchorMax = Vector3.one;
                rectTrans.offsetMin = Vector3.zero;
                rectTrans.offsetMax = Vector3.zero;
                root.AddComponent<CanvasRenderer>();
                root.AddComponent<ObjectBinding>();

                // 创建预设
                PrefabUtility.SaveAsPrefabAsset(root, pathName);

                // 销毁游戏对象，因为我们只需要预设
                DestroyImmediate(root);
            }
        }
    }
}
